package de.edb.ctrl;

import java.security.MessageDigest;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import de.edb.dao.DaoException;
import de.edb.dao.UserDao;
import de.edb.model.User;

@Controller
public class UserController {
	private UserDao userDao = null;

    public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}


    /**
     * <p>Searches for all users and returns them in a 
     * <code>Collection</code>.</p>
     * 
     * <p>Expected HTTP GET and request '/users.html'.</p>
     */
    @RequestMapping(value="/admin/users.html", method=RequestMethod.GET)
    public ModelAndView findAll() {
		ModelAndView mv = new ModelAndView();
		mv.addObject("title", "Benutzer");
		mv.addObject("users", userDao.findAll());
		mv.addObject("tab", "users");
		mv.setViewName("list-users");
		return mv;
    }
    
    /**
     * <p>Saves an User.</p>
     * 
     * <p>Expected HTTP POST and request '/saveuser.html'.</p>
     * @return 
     * @throws DaoException 
     */
    @RequestMapping(value="/admin/saveuser.html", method=RequestMethod.POST)
    public ModelAndView save(User user, Model model) {
    	try {
    		
    		if (user.getPassword().equals("no-change")){
    				user.setPassword(userDao.findById(user.getId()).getPassword());
    		} else {
	    		MessageDigest sha = MessageDigest.getInstance("SHA-256");
	    		sha.update(user.getPassword().getBytes());
	    		user.setPassword(new String(Hex.encode(sha.digest())));
    		}
	        userDao.save(user);
	        return new ModelAndView("redirect:/admin/users.html");
    	} catch (Exception e) {
			ModelAndView mv = new ModelAndView("error");
			mv.addObject("message", e.getMessage());
			return mv;
		}
    }

    /**
     * <p>Deletes an User.</p>
     * 
     * <p>Expected HTTP POST and request '/deleteuser.html'.</p>
     */
    @RequestMapping(value="/admin/deleteuser.html", method=RequestMethod.POST)
    public ModelAndView delete(User user) {
        try {
			userDao.delete(user);
	        return new ModelAndView("redirect:/admin/users.html");
		} catch (DaoException e) {
			ModelAndView mv = new ModelAndView("error");
			mv.addObject("message", e.getMessage());
			return mv;
		}
    }
    
}
